package org.example.sensor.controller;

import lombok.RequiredArgsConstructor;
import org.example.sensor.dto.ChatMessage;
import org.example.sensor.dto.ChatRequest;
import org.example.sensor.dto.ChatResponse;
import org.example.sensor.dto.UserMessage;
import org.example.sensor.service.SparkService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final SparkService sparkService;

    @PostMapping
    public ResponseEntity<?> chat(@RequestBody UserMessage userMessage) {
        ChatRequest request = new ChatRequest();
        request.setModel("4.0Ultra");
        request.setMessages(List.of(
                new ChatMessage("user", userMessage.getContent())
        ));

        try {
            ChatResponse response = sparkService.sendMessage(request);
            return ResponseEntity.ok(response);
        } catch (RestClientException e) {
            return ResponseEntity.status(500)
                    .body(Map.of("error", "API调用失败: " + e.getMessage()));
        }
    }
}